import storage from 'good-storage'
const MAX_LEN = 15
const SEARCH_KEY = '__search__'
const PLAY_KEY = '__play__'
const PLAY_MAX_LEN = 200
const FAVORITE_KEY = '__favorite__'
const FAVORITE_MAX_LEN = 200
function insertHistory (arr, val, compare, maxLen) {
  let index = arr.findIndex(compare)
  if (index >= 0) {
    arr.splice(index, 1)
  }
  arr.unshift(val)
  if (maxLen && arr.length > maxLen) {
    arr.pop()
  }
}

function deleteFromArray (arr, compare) {
  let index = arr.findIndex(compare)
  if (index > -1) {
    arr.splice(index, 1)
  }
}

export function saveSearch (query) {
  let storages = storage.get(SEARCH_KEY, [])
  insertHistory(storages, query, (item) => {
    return item === query
  }, MAX_LEN)
  storage.set(SEARCH_KEY, storages)
  return storages
}
export function loadHistory () {
  return storage.get(SEARCH_KEY, [])
}

export function deleteSearch (query) {
  let storages = storage.get(SEARCH_KEY, [])
  deleteFromArray(storages, (item) => {
    return item === query
  })
  storage.set(SEARCH_KEY, storages)
  return storages
}

export function clearSearch () {
  storage.remove(SEARCH_KEY)
  return []
}

export function savePlay (song) {
  let storages = storage.get(PLAY_KEY, [])
  insertHistory(storages, song, (item) => {
    return item.id === song.id
  }, PLAY_MAX_LEN)
  storage.set(PLAY_KEY, storages)
  return storages
}

export function loadPlayHistory () {
  return storage.get(PLAY_KEY, [])
}

export function saveFavoriteList (song) {
  let storages = storage.get(FAVORITE_KEY, [])
  insertHistory(storages, song, (item) => {
    return item.id === song.id
  }, FAVORITE_MAX_LEN)
  storage.set(FAVORITE_KEY, storages)
  return storages
}

export function deleteFavoriteList (song) {
  let storages = storage.get(FAVORITE_KEY, [])
  deleteFromArray(storages, (item) => {
    return item.id === song.id
  })
  storage.set(FAVORITE_KEY, storages)
  return storages
}

export function loadFavorite () {
  return storage.get(FAVORITE_KEY, [])
}
